import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Index from "../views/Index.vue"

// 引入自己创建的 axios
import axios from "../axios";
import store from "@/store";

Vue.use(VueRouter)

const routes = [
  {
    path: '/home',
    name: 'Home',
    component: Home,
    // 嵌套路由，子路由
    children: [
      // 预加载形式
      {
        path: '/index',
        name: 'Index',
        meta: {
          title: "首页"
        },
        component: Index
      },
      {
        path: '/userCenter',
        name: 'UserCenter',
        meta: {
          title: "个人中心"
        },
        component: () => import(/* webpackChunkName: "about" */ '../views/UserCenter.vue')
      },
      // {
      //   path: '/sys/users',
      //   name: 'User',
      //   component: User
      // },
      // {
      //   path: '/sys/roles',
      //   name: 'SysRole',
      //   component: Role
      // },
      // {
      //   path: '/sys/menus',
      //   name: 'SysMenu',
      //   component: Menu
      // },
    ]
  },
  // 懒加载形式
  {
    path: '/login',
    name: 'Login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    meta: {
      title: "登陆？"
    },
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
  },
  {
    path: '/answer*',
    name: 'Answer',
    component: () => import(/* webpackChunkName: "about" */ '../views/Answer')
  }
]

const router = new VueRouter({
  // mode: 'history',
  // base: process.env.BASE_URL,
  routes
})

// 动态路由
router.beforeEach((to, form, next) => {
  
  let hasRoute = store.state.menus.hasRoutes
  
  let token = localStorage.getItem("token")
  
  console.log("hasRoute: " + hasRoute + ", token: " + !token)
  if (!token && to.path != '/login') {
    next({
      path: '/login',
      query: {
        redirect: to.fullPath
      }
    })
  } else if (to.path == '/login') {
    next()
  } else if (token && !hasRoute) {
    axios.get("/sys/menu/nav", {
      // Authorization: localStorage.getItem("token")
      headers: {
        Authorization: token
      }
    }).then(res => {
      console.log("res.data.data")
      console.log(res.data.data)
      // 拿到 menuList
      store.commit("setMenuList", res.data.data.nav)
      // 拿到用户权限
      store.commit("setPermList", res.data.data.authority)
      
      console.log("store.state.menus.menuList")
      console.log(store.state.menus.permList)
      
      // 动态绑定路由
      let newRoutes = router.options.routes
      
      res.data.data.nav.forEach(menu => {
        if (menu.children) {
          menu.children.forEach(e => {
            // 转换路由
            let route = menuToRoute(e)
            // 把路由添加到路由管理中
            if (route) {
              newRoutes[0].children.push(route)
              // newRoutes.push(route)
            }
          })
        }
      })
      // addRouters弃用了，用这个：newRouters.forEach(newRouter => { router.addRoute(newRouter) })
      console.log("newRoutes")
      console.log(newRoutes)
      // router.addRoutes(newRoutes)
      newRoutes.forEach(newRouter => {
        router.addRoute(newRouter)
      })
      // 路由已经加载，保存状态
      hasRoute = true
      store.commit("changeRouteStatus", hasRoute)
      next({path: '/index'})
    })
  }
  next()
})

// 导航转成路由
const menuToRoute = (menu) => {
  if (!menu.component) {
    return null
  }
  
  let route = {
    name: menu.name,
    path: menu.path,
    meta: {
      icon: menu.icon,
      title: menu.title
    },
    // component: '@/views/'+ menu.component +'.vue'
  }
  route.component = () => import('@/views/' + menu.component + '.vue')
  return route
}

export default router
